<template>
  <!--  面包屑-->
  <div>
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item>课程信息</el-breadcrumb-item>
      <el-breadcrumb-item><b>考勤统计</b></el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <!-- 搜索工具 -->
  <div  class="search-container" style="margin: 40px 0 0 0">
    <el-form :inline="true" ref="searchFormRef" :model="searchFormModel" class="demo-form-inline" style="margin-top: 20px">
      <el-form-item prop="sname">
        <el-input v-model="searchFormModel.sname" placeholder="请输入学生姓名" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchOnSubmit">查询</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 数据表格 -->
  <div style="margin:40px 20px 20px 20px">
    <el-table :data="tableCourse" stripe border style="width: 100%">
      <el-table-column prop="sid" label="学号"  align="center"/>
      <el-table-column prop="sname" label="姓名"  align="center"/>
      <el-table-column prop="signcount" label="实际签到" align="center"/>
      <el-table-column prop="count" label="应签到" align="center"/>
      <el-table-column prop="chour" label="总课时" align="center"/>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button  @click="tableEditHandler(scope.$index, scope.row)">
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 编辑模态框 -->
  <el-dialog v-model="dialogEditState" title="修改考勤信息" width="400px" center>
    <div>
      <el-form ref="formEditRef" :model="formEdit" :rules="editRules" label-width="120px">
        <el-form-item prop="signcount" label="实到次数">
          <el-input v-model="formEdit.signcount"placeholder="必须含有至少两个字"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogEditOnReset">取消</el-button>
        <el-button type="primary" @click="dialogEditOnSubmit">更新</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 分页 -->
  <div class="pagination-container">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5,10]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import request from "@/utils/class";
import {ElMessage} from "element-plus";

//////////////  编辑  ///////////////////////
const editRules = reactive({
  signcount: [
    {required: true, message: '不能为空', trigger: 'blur'},
    {min: 1, max: 2, message: '长度过长', trigger: 'blur'},
    {pattern: /^[0-9]+$/, message: '必须是阿拉伯数字', trigger: 'blur'},
    {validator: (rule, value, callback) => {
        if (value && parseInt(value) > tableCourse.value[0].count) {
          callback(new Error('不能大于“应签到”的值'));
        } else {
          callback();
        }
      }, trigger: 'blur'}
  ]
});

const tableEditHandler = (rowIndex , rowData) => {
  console.log("-------------")
  console.log(rowIndex)
  console.log(rowData)

  formEdit.signcount = rowData.signcount
  formEdit.sid = rowData.sid
  dialogEditState.value = true
}

const dialogEditState = ref(false)

// 编辑对话框的提交处理函数
const dialogEditOnSubmit = () => {
  formEditRef.value.validate((valid) => {
    if (valid) {
      // 校验通过，执行更新操作
      request({
        method: 'POST', // 确保请求方法与后端一致
        url: '/attendence/updateSignCount', // 确保请求 URL 与后端一致
        headers: {'content-type': 'application/json;charset=UTF-8'},
        data: formEdit // 确保发送的数据是正确的
      }).then(req => {
        if (req.data.errorCode === 200) {
          getCourse(); // 刷新课程列表
          ElMessage.success('更新成功');
          // 新增以下代码，自动关闭对话框
          dialogEditState.value = false;
        } else {
          ElMessage.error('更新失败：' + req.data.message); // 显示后端返回的错误信息
        }
      }).catch(error => {
        ElMessage.error('请求失败：' + error.message); // 显示请求错误信息
      });
    } else {
      // 校验失败，显示错误消息
      ElMessage.error('表单校验失败');
    }
  });
};

const dialogEditOnReset = () => {
  // 清空表单数据
  Object.assign(formEdit , formEditData)
  // 关闭对话框
  dialogEditState.value = false
}

// 新增表单引用
const formEditRef = ref()

// 新增表单初始化数据
const formEditData = {
  signcount : ''
}

// 编辑表单绑定数据模型
const formEdit = reactive({...formEditData})

////////////////表格///////////////////////
onMounted(()=>{
  getCourse();
})

//表格信息显示
const tableCourse = ref([]);
let totals = ref(0)
const getCourse = () => {
  //获取cid
  const selectedCid = sessionStorage.getItem('selectedCid');

  const params = {
    cid: selectedCid,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  };
// 判断是否有搜索条件，如果有，则添加到请求参数中
  if (searchFormModel.sname && searchFormModel.sname.trim() !== '') {
    params.sname = searchFormModel.sname.trim();
  }
  request({
    url: '/attendence/all',
    method: 'get',
    params,
  }).then(req => {
    console.log(req)
    console.log(req.data)
    if (200 == req.data.errorCode) {
      tableCourse.value = req.data.data.records;
      totals.value = req.data.data.total;
    }
  })
}
/////////  搜索框  ////////////////
const searchFormRef=ref()

const searchFormModel=reactive({
  sname:''
})

const searchOnSubmit=()=>{
  getCourse();
}

const searchOnReset=()=>{
  searchFormModel.sname=''
}




//分页
const currentPage = ref(1)
const pageSize = ref(10)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  pageSize.value=val;
  getCourse()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  currentPage.value=val;
  getCourse()
}
</script>

<style scoped>
.el-breadcrumb {
  font-size: 18px;
  margin: 20px;
}

/* 分页居中样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin: 20px auto; /* 根据需要调整外边距 */
}
</style>